package com.defysoft.waukids.notice;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Type.BC_NOTICE;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Notice_Detail_A extends BaseActivity implements OnClickListener {
	private SharedPreferences member;	//부모,원장,선생님
	String notice_code;	//공지idx
	TextView tv[] = new TextView[6];
	ImageView imageView;
	final int SELECT_NOTICE = 1; // 공지 불러오기
	final int DELETE_NOTICE = 2; // 공지 삭제하기
	final int SUCCESS_DELETE = 3; // 공지 삭제 완료
	final int FAIL_DELETE = 4; // 공지 삭제 실패
	
	private final int NONE_NOTICE = 9;		//내용못불러옴.
	private final int SUCCESS_SEARCH= 10;	//내용불러옴.
	BC_NOTICE bcNotice;
	//스피너
	Toolbar toolbar;
	Spinner spinner;
	String[] celebrities = {"수 정","삭 제"};
	
	//이미지 세팅
	DisplayImageOptions options; 
	ImageLoader imageLoader;
	//수정.삭제버튼
	LinearLayout linearLayout;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == NOTICE_EDIT) {
			setResult(TOOLBAR_BACK, data);
			setStartToolbar();
			startNetwork(1);
		}
	}
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		notice_code=getIntent().getStringExtra("notice_code");
		setContentView(R.layout.notice_detail_a);
		setStartData();
		setStartToolbar();	//툴바설정
		startNetwork(SELECT_NOTICE);
	}

	@Override
	public void setStartData() {
		super.setStartData();
		tv[0] = (TextView)findViewById(R.id.NOTICE_DETAIL_NAME);//제목
		tv[1] = (TextView)findViewById(R.id.NOTICE_DETAIL_SUB);	//내용
		tv[2] = (TextView)findViewById(R.id.NOTICE_DETAIL_DATE);//날짜
		tv[3] = (TextView)findViewById(R.id.NOTICE_DETAIL_RAGE);//조회수
		tv[4] = (TextView)findViewById(R.id.NOTICE_DETAIL_WRITE);//수정버튼
		tv[5] = (TextView)findViewById(R.id.NOTICE_DETAIL_DELETE);//삭제버튼
		for (int i = 0; i < tv.length; i++) {
			tv[i].setOnClickListener(this);
		}
		imageView = (ImageView)findViewById(R.id.NOTICE_DETAIL_IMG);		//사진
		imageView.setOnClickListener(this);
		member = getSharedPreferences("member", MODE_PRIVATE);
		//학부모는 아예 수정/삭제 안보이기.
		toolbar = (Toolbar)findViewById(R.id.NOTICE_DETAIL_TOOL);
		spinner = (Spinner)findViewById(R.id.NOTICE_SPI);
		linearLayout = (LinearLayout)findViewById(R.id.NOTICE_DETAIL_WRITE_DELETE_LL);
		linearLayout.setVisibility(View.GONE);
		
		//이미지 세팅.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();
		imageLoader.clearDiskCache();
		imageLoader.clearMemoryCache();

		options = new DisplayImageOptions.Builder().cacheInMemory(true)
				.showImageOnFail(R.drawable.logo)
				/*.imageScaleType(ImageScaleType.EXACTLY)*/
				.cacheOnDisc(true)
				.considerExifParams(true).build();
	}
	private void setStartToolbar(){	//툴바설정.
		spinner.setAdapter(
				new ArrayAdapter<String>(this, 0){
			@Override
			public int getCount() {
				return celebrities.length;
			}
			@Override
			public View getDropDownView(int position, View convertView,
					ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
            ((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setText(celebrities[position]);
				convertView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						switch (pos) {
						case 0:
							Intent i =new Intent(Notice_Detail_A.this, Notice_Detail_Edit_A.class)
										.putExtra("PK_Not_Code", bcNotice.PK_Not_Code+"")
										.putExtra("mode","update");
								startActivityForResult(i, NOTICE_EDIT);
							break;
						case 1:
							startNetwork(DELETE_NOTICE);
							break;
							
						}
					}
				});
				return convertView;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setBackgroundColor(0x00ffffff);
				return convertView;
			}
		});
		
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		spinner.setVisibility(View.INVISIBLE);
	}
	

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho=choice;
		if (firstThread != null) {firstThread.interrupt();}
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case SELECT_NOTICE:
					mainThread();
					break;
				case DELETE_NOTICE:	
					deleteThread();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}

			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG).show();
			break;
		case NONE_NOTICE:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}

			break;
		case SUCCESS_SEARCH:
			//수정,삭제버튼 설정
			if (bcNotice.FK_Cla_Not_Code == 0) {	//전체공지
				if (member.getString("Mem_Rank", "").equals("1")) {
					spinner.setVisibility(View.INVISIBLE);
					linearLayout.setVisibility(View.VISIBLE);
				} else {linearLayout.setVisibility(View.GONE);}
			} else {	//반 공지
				if (member.getString("Mem_Rank", "").equals("2")) {
					spinner.setVisibility(View.INVISIBLE);
					linearLayout.setVisibility(View.VISIBLE);
				} else {linearLayout.setVisibility(View.GONE);}
			}	
			//이미지유무.
			if (bcNotice.Not_Photo.length() > 5) {
				findViewById(R.id.NOTICE_DETAIL_IMG_LL).setVisibility(View.VISIBLE);
				imageLoader.displayImage(PublicConstant.FTP_NOTICE_PHOTO+bcNotice.Not_Photo, imageView, options, null);			
			}
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			tv[0].setText(bcNotice.Not_Name);
			tv[1].setText(bcNotice.Not_Sub);
			tv[2].setText(bcNotice.Not_Date);
			tv[3].setText("조회수 : "+bcNotice.Not_Rage);
			break;
		case SUCCESS_DELETE:	//삭제성공
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(Notice_Detail_A.this,"삭제완료하였습니다.",Toast.LENGTH_SHORT).show();
			Intent i = new Intent();
			if (member.getString("Mem_Rank", "").equals("2")) {	//선생
				setResult(TOOLBAR_BACK, i.putExtra("Mem_Rank", "2"));				
			} else if (member.getString("Mem_Rank", "").equals("1")) {	//원장.
				setResult(TOOLBAR_BACK, i.putExtra("Mem_Rank", "1"));
			}
			finish();
			break;			
		case FAIL_DELETE:	//삭제실패
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(Notice_Detail_A.this,(String)_message.obj,Toast.LENGTH_SHORT).show();
			
			break;			
		}	
	}


	@Override
	public void onClick(View v) {
		Intent i;
		switch (v.getId()) {
		case R.id.NOTICE_DETAIL_IMG:	//사진 클릭시.
			i = new Intent(Notice_Detail_A.this, Notice_Detail_Photo_A.class)
						.putExtra("photo", PublicConstant.FTP_NOTICE_PHOTO+bcNotice.Not_Photo);
			startActivity(i);
			break;
		case R.id.NOTICE_DETAIL_NAME:	//이름 클릭시.
			
			if (bcNotice.FK_Cla_Not_Code == 0) {	//전체공지
				if (member.getString("Mem_Rank", "").equals("1")) {
					//수정,삭제버튼 설정
					i =new Intent(Notice_Detail_A.this, Notice_Detail_Edit_A.class)
					.putExtra("PK_Not_Code", bcNotice.PK_Not_Code+"")
					.putExtra("mode","update");
					startActivityForResult(i, NOTICE_EDIT);
				} 
			} else {	//반 공지
				if (member.getString("Mem_Rank", "").equals("2")) {
					//수정,삭제버튼 설정
					i =new Intent(Notice_Detail_A.this, Notice_Detail_Edit_A.class)
					.putExtra("PK_Not_Code", bcNotice.PK_Not_Code+"")
					.putExtra("mode","update");
					startActivityForResult(i, NOTICE_EDIT);
				}
			}
			
			break;
		case R.id.NOTICE_DETAIL_SUB:	//내용 클릭시.
			if (bcNotice.FK_Cla_Not_Code == 0) {	//전체공지
				if (member.getString("Mem_Rank", "").equals("1")) {
					//수정,삭제버튼 설정
					i =new Intent(Notice_Detail_A.this, Notice_Detail_Edit_A.class)
					.putExtra("PK_Not_Code", bcNotice.PK_Not_Code+"")
					.putExtra("mode","update");
					startActivityForResult(i, NOTICE_EDIT);
				} 
			} else {	//반 공지
				if (member.getString("Mem_Rank", "").equals("2")) {
					//수정,삭제버튼 설정
					i =new Intent(Notice_Detail_A.this, Notice_Detail_Edit_A.class)
					.putExtra("PK_Not_Code", bcNotice.PK_Not_Code+"")
					.putExtra("mode","update");
					startActivityForResult(i, NOTICE_EDIT);
				}
			}
			break;
		case R.id.NOTICE_DETAIL_WRITE:	//수정하기
			i =new Intent(Notice_Detail_A.this, Notice_Detail_Edit_A.class)
			.putExtra("PK_Not_Code", bcNotice.PK_Not_Code+"")
			.putExtra("mode","update");
			startActivityForResult(i, NOTICE_EDIT);		
			break;
		case R.id.NOTICE_DETAIL_DELETE:
			dialog_delete();
			break;
		}
	}
	private void dialog_delete() {
		AlertDialog.Builder builder = new AlertDialog.Builder(Notice_Detail_A.this);
		builder.setMessage("공지를 삭제 하겠습니까?")
			   .setCancelable(false)
			   .setPositiveButton("네", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					startNetwork(DELETE_NOTICE);	
					dialog.cancel();
				}
			})
			.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	protected void mainThread() {	//공지 불러오기
		try{
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_NOTICE_DETAIL
					, "notice_code="+notice_code+"&PK_Mem_Email="+member.getString("PK_Mem_Email", "")));
			if (jsonObject.getBoolean("success")) {	
				bcNotice = JsonParser.NoticeDetail(jsonObject.getString("payload"));
				onNetworkCallback(SUCCESS_SEARCH,"" );
			} else {
				onNetworkCallback(NONE_NOTICE, jsonObject.getString("message"));
			}
		}catch(Exception e){
			onNetworkCallback(CATCH_EXCEPTION, "main"+e.toString());		
		}
	}
	protected void deleteThread() {	//삭제하기
		try{
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_NOTICE_DELETE, 
					"notice_code="+notice_code+"&Not_Photo="+bcNotice.Not_Photo));
			if (jsonObject.getBoolean("success")) {	
				bcNotice = JsonParser.NoticeDetail(jsonObject.getString("payload"));
				onNetworkCallback(SUCCESS_DELETE,"" );
			} else {
				onNetworkCallback(FAIL_DELETE, jsonObject.getString("message"));
			}
		}catch(Exception e){
			onNetworkCallback(CATCH_EXCEPTION, "main"+e.toString());		
		}
	}
}
